<template>
  <div class="body-box" @click="blurSearch">
    <el-form
      size="mini"
      label-position="right"
      label-width="80px"
      :model="form"
      :rules="rules"
      ref="form"
      v-loading = "add_load"
      :disabled="team_id ? true : false"
    >
      <el-form-item label="团报名称" prop="name">
        <el-input placeholder="请输入团报名称" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="开启密码">
        <!-- <el-switch
          v-model="form.open_pwd"
          @change="changeOpen"
          active-color="#8a70c6"
          inactive-color="#e1e1e1"
        ></el-switch> -->
        <el-input
          placeholder="请输入密码（不输入表示不启用）"
          type="text"
          v-model="form.password"
          class="form-inline-input"
        ></el-input>
      </el-form-item>
      <el-form-item label="限定跑团">
        <el-switch v-model="form.limit_team" active-color="#8a70c6" inactive-color="#e1e1e1"></el-switch>
        <div v-if="form.limit_team">
          <div class="search-teams" @click.stop>
            <el-input
              placeholder="请输入跑团名称搜索"
              @input="searchTeam()"
              v-model="search_name"
              @focus="focusSearch"
            ></el-input>
            <ul class="search-list" v-if="seach_show">
              <li v-for="(item,key) in team_list" :key=" key">
                <div class="search-name">{{item.Title}}</div>
                <el-button
                  size="mini"
                  class="com-btn select-search"
                  @click="selectTeam(item,key)"
                >选择</el-button>
              </li>
            </ul>
          </div>
          <el-table size="mini" border :data="form.team_list">
            <el-table-column type="index" width="50px"></el-table-column>
            <el-table-column label="Logo" width="60px">
              <template slot-scope="item">
                <el-image :src="item.row.Logo" fit="cover" class="team-logos"></el-image>
              </template>
            </el-table-column>
            <el-table-column label="跑团名称" prop="Title"></el-table-column>
            <el-table-column label="团长" prop="Contacter"></el-table-column>
            <el-table-column label="城市" prop="City" width="150px"></el-table-column>
            <el-table-column label="操作" width="50px">
              <template slot-scope="item">
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  circle
                  class="com-btn"
                  @click="deleteTeam(item)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item label="团报基数">
        <!-- <el-switch
          v-model="form.open_base"
          @change="changeOpenBase"
          active-color="#8a70c6"
          inactive-color="#e1e1e1"
        ></el-switch> -->
        <el-input
          placeholder="请输入团报基数（不输入表示无基数）"
          type="number"
          v-model="form.base_num"
          class="form-inline-input"
        ></el-input>
        <div class="base-num-txt">
          备注：团报基数代表用户享受团报价格的最低报名人数总和。如某组别报名标准价为100元，团报价格80元。团报基数为30人，那么该团报名额满30人（包含30）后，
          系统会自欧东在报名结束的时候退还20元差价。
        </div>
      </el-form-item>
      <el-form-item label="报名设置" prop="team_info">
        <el-table
          size="mini"
          border
          v-loading="load_team"
          :data="team_info"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="41"></el-table-column>
          <el-table-column label="组别" prop="name"></el-table-column>
          <el-table-column label="使用次数">
            <template slot-scope="item">
              <el-input placeholder="请输入使用次数" v-model="item.row.num" type="number" @input="checkTeamNum(item.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="价格">
            <template slot-scope="item">
              <el-input placeholder="请输入价格" v-model="item.row.price" type="number" @input="checkTeamPrice(item.$index)"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="团报总数" prop="total_people">
        <el-input placeholder="请输入团报总人数" v-model="form.total_people" type="number">
          <template slot="append">人</template>
        </el-input>
      </el-form-item>
      <el-form-item label="有效期" prop="end_time">
        <el-date-picker
          v-model="form.start_time"
          type="datetime"
          placeholder="选择日期时间"
          value-format="timestamp"
          @change="selectStarttime"
        ></el-date-picker>
        <span style="padding:0 10px;">至</span>
        <el-date-picker
          v-model="form.end_time"
          type="datetime"
          placeholder="选择日期时间"
          value-format="timestamp"
          @change="seletcEndtime"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button class="com-btn" size="mini" @click="submit('form')" v-if="!team_id">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: { active_id: {} , team_id : {}},
  data() {
    return {
      form: {
        name: "",
        password: "",
        open_pwd: false,
        limit_team: false,
        team_list: [],
        base_num: "",
        open_base: false,
        team_info: [],
        total_people: "",
        start_time: "",
        end_time: ""
      },
      rules: {
        name: [{ required: true, message: "请输入团报名称", trigger: "blur" }],
        password: [
          { required: true, message: "请输入团报密码", trigger: "blur" }
        ],
        base_num: [
          { required: true, message: "请输入团报基数", trigger: "blur" }
        ],
        team_info: [{ required: true, message: "请选择组别", trigger: "blur" }],
        total_people: [
          { required: true, message: "请输入团报总人数", trigger: "blur" }
        ],
        start_time: [
          { required: true, message: "请输入团报有效期", trigger: "blur" }
        ],
        end_time: [
          { required: true, message: "请输入团报有效期", trigger: "blur" }
        ]
      },
      search_name: "",
      team_list: [],
      seach_show: false,
      load_team: true,
      team_info: [],
      add_load : false
    };
  },
  mounted() {
    this.getActiveTeamInfo();
    if(this.team_id > 0)this.getInfo();
  },
  methods: {
    //更改组别数量
    checkTeamNum(index){
      if(this.team_info[index].num < 0){
        this.toast(0,'数量不能小于0');
        this.team_info[index].num = '';
      }
    },
    //检测组别团报价格正确性
    checkTeamPrice(index){
      if(this.team_info[index].price < 0){
        this.toast(0,'价格不能小于0');
        this.team_info[index].price = '';
      }
    },
    //获取团报信息
    getInfo(){
        this.ajaxs('active/getTeampaperInfo',{
            data:{ id : this.team_id},
            success:(res) => {
                this.form = res.msg;
                this.team_info = res.msg.team_info;
                this.form.end_time = this.form.end_time * 1000;
                this.form.start_time = this.form.start_time * 1000;
                console.log(this.form);
            }
        });
    },
    //保存
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.active_id = this.active_id;
          
          for(var i in this.form.team_info) {
              if(this.form.team_info[i].num == '')return this.toast(0,'请输入次数');
              if(this.form.team_info[i].price == '')return this.toast(0,'请输入价格');
          }
          this.add_load = true;
          this.ajaxs("active/addTeampaper", {
            data: this.form,
            success: res => {
              this.toast(res.code, res.msg);
              if (res.code) {
                setTimeout(()=>{
                    this.$parent.getData();
                    this.$parent.$layer.closeAll();
                },1000);
              }
              this.add_load = false;
            }
          });
        }
      });
    },
    //选择结束时间
    seletcEndtime() {
      if (this.form.start_time == "") {
        this.form.end_time = "";
        return this.toast(0, "请先选择结束时间");
      }
      if (this.form.end_time < this.form.start_time) {
        this.form.end_time = "";
        return this.toast(0, "结束时间要大于开始时间");
      }
    },
    //选择开始时间
    selectStarttime() {
      if (this.form.end_time < this.form.start_time && this.form.end_time) {
        this.form.end_time = "";
        return this.toast(0, "结束时间要大于开始时间");
      }
    },
    //选择活动组别
    handleSelectionChange(e) {
      this.form.team_info = e;
    },
    //获取组别信息
    getActiveTeamInfo() {
      this.ajaxs("active/getTeamInfo", {
        data: { active_id: this.active_id },
        success: res => {
          this.load_team = false;
          var data = res.msg;
          for (var i in data) {
            this.team_info.push({
              id: data[i].id,
              name: data[i].name,
              num: "",
              price: ""
            });
          }
        }
      });
    },
    //改变密码开关
    changeOpen() {
      this.form.password = "";
    },
    changeOpenBase(){
        this.form.base_num = '';
    },
    //搜索框聚焦
    focusSearch() {
      this.seach_show = true;
    },
    //搜索框失去焦点
    blurSearch() {
      this.seach_show = false;
    },
    //搜索跑团
    searchTeam() {
      this.ajaxs("active/searchTeam", {
        data: { name: this.search_name },
        success: res => {
          var data = res.msg;
          this.team_list = [];
          for (var i in data) {
            if (this.checkInTeam(data[i].Id)) this.team_list.push(data[i]);
          }
        }
      });
    },
    //判断是会否存在
    checkInTeam(str) {
      for (var x in this.form.team_list) {
        if (this.form.team_list[x].Id == str) return false;
      }
      return true;
    },
    //选择跑团
    selectTeam(data, key) {
      this.form.team_list.push({
        Id: data.Id,
        Title: data.Title,
        Logo: data.Logo,
        City: data.City,
        Contacter: data.Contacter
      });
      this.team_list.splice(key, 1);
      this.seach_show = false;
      this.$forceUpdate();
    },
    //删除跑团
    deleteTeam(data) {
      this.form.team_list.splice(data.$index, 1);
    }
  }
};
</script>

<style>
.base-num-txt {
  font-size: 12px;
  color: #999;
  line-height: 20px;
}
.select-search {
  float: right;
}
.search-name {
  float: left;
  color: #666;
}
.search-list > li {
  overflow: hidden;
  padding: 5px 10px;
  border-bottom: 1px solid #e1e1e1;
  cursor: pointer;
}
.search-list {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: #fff;
  z-index: 9999;
  box-shadow: 1px 1px 3px rgba(26, 26, 26, 0.3);
}
.search-teams {
  margin: 10px 0;
  position: relative;
}
.form-inline-input {
  width: 300px;
  /* margin-left: 20px; */
}
.team-logos {
  height: 28px;
  width: 28px;
  border-radius: 50%;
  vertical-align: middle;
}
</style>